package com.mopon.service.user;

import java.util.concurrent.Future;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;

import rx.Observable;
import rx.Subscriber;

public class UserService {

	@HystrixCommand(groupKey = "UserGroup", commandKey = "GetUserByIdCommand", fallbackMethod = "fallback1")
	public User getUserById(String id, String name) {
		// return userResource.getUserById(id);
		return null;
	}

	@HystrixCommand
	public Future<User> getUserByIdAsync(final String id) {
		return new AsyncResult<User>() {
			@Override
			public User invoke() {
				// return userResource.getUserById(id);
				return null;
			}
		};
	}

	@HystrixCommand

	public Observable<User> getUserById(final String id) {
		return Observable.create(new Observable.OnSubscribe<User>() {
			@Override
			public void call(Subscriber<? super User> observer) {
				try {
					if (!observer.isUnsubscribed()) {
						observer.onNext(new User(id, "" + id));
						observer.onCompleted();
					}
				} catch (Exception e) {
					observer.onError(e);
				}
			}
		});
	}

	@HystrixCommand(fallbackMethod = "fallback2")
	User fallback1(String id, Throwable e) {
		assert "getUserById command failed".equals(e.getMessage());
		throw new RuntimeException("fallback1 failed");
	}

	@HystrixCommand(fallbackMethod = "fallback3")
	User fallback2(String id) {
		throw new RuntimeException("fallback2 failed");
	}

	@HystrixCommand(ignoreExceptions = { BadRequestException.class })
	public User getUserById(int id) {
		// return userResource.getUserById(id);
		return null;
	}

	@HystrixCommand(groupKey = "UserGroup", commandKey = "GetUserByIdCommand", commandProperties = {
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500") }, threadPoolProperties = {
					@HystrixProperty(name = "coreSize", value = "30"),
					@HystrixProperty(name = "maxQueueSize", value = "101"),
					@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
					@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
					@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "12"),
					@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1440") })
	public User getUserById(long id) {
		return null;
	}
}
